#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from datetime import datetime, timedelta


def timemake(n=None, y=None, r=None, s=None, f=None, m=None, w=None):
    """
    datetime_set:
        timemake(y=1, r="2", s="-1", f="+2") =>
            month = 1
            day = 2
            hour = now_hour - 1
            minute = now_minute + 2

    hour: 2, minute: +70 => hour: 3, minute: + 10
    """
    now = datetime.now()

    nn_delta = None
    yy_delta = None
    rr_delta = None
    ss_delta = None
    ff_delta = None
    mm_delta = None
    ww_delta = None

    def getdelta(x):
        if x is None:
            return None

        if str(x)[0] in ("+-"):
            return int(x)

        return None

    nn_delta = getdelta(n)
    if nn_delta is not None:
        nn = now.year + nn_delta
    elif y is None:
        nn = now.year
    else:
        nn = int(n)

    yy_delta = getdelta(y)
    if yy_delta is not None:
        yy = now.month + yy_delta
        nn += int(yy_delta / 12)
        yy = int((yy - 1) % 12) + 1
    elif y is None:
        yy = now.month
    else:
        yy = int(y)

    rr_delta = getdelta(r)
    if rr_delta is not None or r is None:
        rr = now.day
    else:
        rr = int(r)

    ss_delta = getdelta(s)
    if ss_delta is not None or s is None:
        ss = now.hour
    else:
        ss = int(s)

    ff_delta = getdelta(f)
    if ff_delta is not None or f is None:
        ff = now.minute
    else:
        ff = int(f)

    mm_delta = getdelta(m)
    if mm_delta is not None or m is None:
        mm = now.second
    else:
        mm = int(m)

    ww_delta = getdelta(w)
    if ww_delta is not None or w is None:
        ww = now.microsecond
    else:
        ww = int(w)

    days = rr_delta if rr_delta is not None else 0
    hours = ss_delta if ss_delta is not None else 0
    minutes = ff_delta if ff_delta is not None else 0
    seconds = mm_delta if mm_delta is not None else 0
    microseconds = ww_delta if ww_delta is not None else 0
    tmdelta = timedelta(
        days=days,
        hours=hours,
        minutes=minutes,
        seconds=seconds,
        microseconds=microseconds,
    )

    ret = datetime(nn, yy, rr, ss, ff, mm, ww) + tmdelta
    return ret


def timediff(n=None, y=None, r=None, s=None, f=None, m=None, w=None):
    """Time diff to now"""
    delta = timemake(n, y, r, s, f, m, w) - datetime.now()
    seconds = delta.total_seconds()
    return seconds


if __name__ == "__main__":
    from mie.xlogger.klog import klog

    klog.to_stdout()

    # timediff(n="+1", y=None, r=None, s=None, f=None, m=None, w=None)
    # timediff(n="+1", y="-1", r=None, s=None, f=None, m=None, w=None)
    # timediff(n="+1", y="-14", r=None, s="-11", f="+40", m=None, w=None)
    # timediff(n="11", y="4", r=None, s="11", f="40", m=33, w=44)
    # timediff(r="+1", s="1", f=0, m=0, w=0)
    # timediff(f="+1", m="-60", w="+10000")
    # timediff(r="+1", s=1, f=0, m=0, w=0)
    klog.d(timediff(f="+1", w="+0"))
